import json
import datetime


class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age


class TimeEncoder(json.JSONEncoder):
    def default(self, obj):
        # print('123')
        if isinstance(obj, datetime.datetime):
            return obj.isoformat(sep=' ', timespec='seconds')


        return super().default(obj)

class TimeDecoder(json.JSONDecoder):
    def decode(self, s: str) :
        # 先让默认解码器跑一遍，拿到 Python 对象
        obj = super().decode(s)
        # 如果是纯字符串且符合格式，就转 datetime
        if isinstance(obj, str):
            try:
                return datetime.datetime.strptime(obj, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                print('未知错误')
        return obj

def hook_datetime(dct):
    """递归地把符合格式的时间字符串转成 datetime"""
    for k, v in dct.items():
        if isinstance(v, str):
            try:
                dct[k] = datetime.datetime.strptime(v, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                pass
        elif isinstance(v, dict):
            dct[k] = hook_datetime(v)
    return dct

class PersonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Person):
            return {'name': obj.name, 'age': obj.age}

        return super().default(obj)

datas = {
    'id':101,
    'f':3.14,
    'b':False,
    's':'ni hao',
    'n':None,
    'l': [1, 2, 3],
    'd':{
        'a':1,
    },
    't':(1,2,3),
    # 'set':{1,2,3},
    'now':datetime.datetime.now(),
    # 'p': Person('Alice', 18),
}

# print(json.dumps(datas, ensure_ascii=False,cls=PersonEncoder))
te = json.dumps(datas, cls=TimeEncoder)
print(te, type(te))

json_str = '"2025-11-03 23:45:00"'
dt = json.loads(json_str, cls=TimeDecoder)
print(dt, type(dt))

data = json.loads(json_str, object_hook=hook_datetime)
print(data, type(data))
